package cn.tedu.weibo.controller;

import cn.tedu.weibo.mapper.UserMapper;
import cn.tedu.weibo.pojo.dto.UserLoginDto;
import cn.tedu.weibo.pojo.dto.UserRegDto;
import cn.tedu.weibo.pojo.entity.User;
import cn.tedu.weibo.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserMapper mapper;
    @RequestMapping("/reg")
    public int reg(@RequestBody UserRegDto userRegDto){
        UserVO u = mapper.selectByUsername(userRegDto.getUsername());
        if(u!=null){
            return 2;
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDto,user);
        return mapper.insert(user);
    }

    @RequestMapping("/login")
    public int login(@RequestBody UserLoginDto userLoginDto, HttpSession session){
        UserVO userVo = mapper.selectByUsername(userLoginDto.getUsername());
        if(userVo!=null){
            if(userVo.getPassword().equals(userLoginDto.getPassword())){
                session.setAttribute("user",userVo);
                return 1;
            }
            return 2;
        }
        return 3;
    }

    @RequestMapping("/currentUser")
    public UserVO currentUser(HttpSession session){
        return (UserVO)session.getAttribute("user");
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }
}
